package com.example.demo.listener.task;

import org.quartz.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * <p>Description: TaskService</p>
 *
 * @author Eric Lee
 * @version v1.0.0
 * @since 2021/8/2 16:15
 **/

@Service(value = "taskService")
public class TaskServiceImpl implements TaskService {

    @Autowired
    private Scheduler scheduler;

    @Override
    public void updateOrInsert(Plan plan) throws Exception {
        // 这里获取任务信息数据
        TriggerKey triggerKey = TriggerKey.triggerKey(plan.getName(), plan.getGroup());
        // 获取trigger，即在spring配置文件中定义的 bean id="myTrigger"
        CronTrigger trigger = (CronTrigger) scheduler.getTrigger(triggerKey);
        if (null == trigger) {
            addJob(plan);
        } else {
            updateOrInsertJob(plan);
        }
    }

    @Override
    public void updateOrInsertJob(Plan plan) throws Exception {
        // 采用的方式是：先删除后新增
        this.delJob(plan);
        this.addJob(plan);
    }

    @SuppressWarnings({"unchecked", "rawtypes"})
    @Override
    public void addJob(Plan plan) throws Exception {
        Class clazz = Class.forName(plan.getJobClass());
        JobDetail jobDetail = JobBuilder.newJob(clazz).withIdentity(plan.getName(), plan.getGroup()).build();
        jobDetail.getJobDataMap().put("planKey", plan);
        // 表达式调度构建器
        CronScheduleBuilder scheduleBuilder = CronScheduleBuilder.cronSchedule(plan.getCron_expression());
        // 按新的cronExpression表达式构建一个新的trigger
        CronTrigger trigger = TriggerBuilder.newTrigger().withIdentity(plan.getName(), plan.getGroup()).withSchedule(scheduleBuilder).build();
        scheduler.scheduleJob(jobDetail, trigger);
        // job.getIsTrue()为0表示停止
        if ("0".equals(plan.getIsTrue())) {
            this.stopJob(plan);
        }
    }

    @Override
    public void stopJob(Plan plan) throws Exception {
        scheduler.pauseJob(new JobKey(plan.getName(), plan.getGroup()));
    }

    @Override
    public void startJob(Plan plan) throws Exception {
        scheduler.resumeJob(new JobKey(plan.getName(), plan.getGroup()));
    }

    @Override
    public void delJob(Plan plan) throws Exception {
        scheduler.deleteJob(new JobKey(plan.getName(), plan.getGroup()));
    }

    @Override
    public void runJob(Plan plan) throws Exception {
        scheduler.triggerJob(new JobKey(plan.getName(), plan.getGroup()));
    }

}
